package com.example.c5c6;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class ContextServletTest extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletContext context = this.getServletContext();
        InputStream Stream =context.getResourceAsStream("/WEB-INF/classes/com/example/c5c6/config.properties");
        Properties properties = new Properties();
        properties.load(Stream);
        String dbName=properties.getProperty("dbName");
        String suerName=properties.getProperty("suerName");
        String userpassword=properties.getProperty("userpassword");
        String url=properties.getProperty("url");
        url=url+dbName+"?suerName="+suerName+"&userpassword="+userpassword;
        try{
            Class.forName("com.mysql.jsp.jdbc.Driver");
            Connection conn= DriverManager.getConnection(url);
            Statement statment=conn.createStatement();
            String sql="select*from student ORDER BY stuclass DESC,number ASC";
            ResultSet rs=statment.executeQuery(sql);
            out.println("<table border=1>");

            out.println("<th colspan=4 style = 'font-size:x-large;alignment;center>学生信息表</th>");
            out.println("<tr style='text-align:center;'>");
            out.println("<td>学号</td> <td>姓名</td> <td>出生日期</td> <td>所在班级</td> </tr>");
            while (rs.next()){
                out.println("<tr style='text-align:center;'>");
                out.println("<td>"+rs.getString(1)+"</td>");
                out.println("<td>"+rs.getString(2)+"</td>");
                out.println("<td>" +rs.getString("birthday")+"</td>");
                out.println("<td>" +rs.getString("stucalss")+"</td>");
                out.println("</tr>");
            }
            out.println("</table> </body>");
        }catch (Exception e){
            e.printStackTrace();
        }
        out.flush();
        out.close();

    }
}
